package com.jeejam.cart.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;

//import com.jeejam.member.pojo.Member;
import com.jeejam.product.pojo.Product;
import com.jeejam.product.service.ProductService;
import com.jeejam.cart.dao.CartMapper;
import com.jeejam.cart.pojo.Cart;
import com.jeejam.cart.pojo.CartItem;
import com.jeejam.cart.service.CartItemService;
import com.jeejam.cart.service.CartService;
import com.jeejam.common.util.CookieUtil;
import com.jeejam.framework.base.service.impl.BaseServiceImpl;

@Service
public class CartServiceImpl extends BaseServiceImpl implements CartService{

	private CartMapper cartMapper;
	
	private CartItemService cartItemService;
	
	private ProductService productService;

	@Resource
	public void setCartMapper(CartMapper cartMapper) {
		this.cartMapper = cartMapper;
		this.baseMapper = cartMapper;
	}
	
	@Resource
	public void setCartItemService(CartItemService cartItemService) {
		this.cartItemService = cartItemService;
	}

	@Resource
	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	/**
	 * 用户没有登录 添加商品到购物车
	 * 
	 * @author karlzhou 
	 */
	@Override
	public void add( Cart currentCart,CartItem cartItem, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (cartItem.getProductId() != 0) {
			// 从cookie获取购物车
			Cart cart = this.getCartByCookie(request);
//			cart.setProvince(currentCart.getProvince());
//			cart.setCity(currentCart.getCity());
//			cart.setDistrict(currentCart.getDistrict());
			
			List<CartItem> items = cart.getItems(); 
			//System.out.println(items);
			String cartStr = "";
			// 当用户从cookie获取不到购物车数据时，再从数据库中获取
			if (items.size() <= 0) {
				//items = new ArrayList<CartItem>();
				items.add(cartItem);
			} else {
				for (CartItem item : items) {
					if (item.getProductId() == cartItem.getProductId()) {
						item.setCount(item.getCount() + cartItem.getCount());// 购买相同的商品，更新数量
						cartItem = null;
						break;
					} 
				}
				if(cartItem != null){
					items.add(cartItem);
				}
			}
			//System.out.println("cart : " + cart);
			
			cartStr = this.parse(cart);
			//System.out.println("cart str : " + cartStr);
			if (cartStr != null && !"".equals(cartStr)) {
				cartStr = cartStr.substring(0, cartStr.length() - 2);
				CookieUtil.addCookie(response, "shopcart", URLEncoder.encode(cartStr, "utf-8"), 3600 * 24 * 7);
				
			}
		}
	}
	
	
	/**
	 * 从cookie获取购物车
	 * 
	 * @author Karlzhou
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@Override
	public Cart getCartByCookie(HttpServletRequest request) throws Exception {
		
		// 获取当前用户购物车cookie
		Cookie cartCookie = CookieUtil.getCookieByName(request, "shopcart");
		
		if (cartCookie == null) {
			return new Cart();
		}
		String cartStr = URLDecoder.decode(cartCookie.getValue(), "utf-8");// 从cookie获取购物车
		System.out.println("cookie cart str : " + cartStr);
		return this.translat(cartStr);
	}

	@Override
	public String parse(Cart cart) {
		StringBuffer buffer = new StringBuffer();
//		buffer.append((cart.getId() == null ? 0 : cart.getId()) + "=" + cart.getProvince() + "=" + cart.getCity() + "=" + cart.getDistrict() + "===");
		// 封装购物车数据到cookie中
		for (CartItem item : cart.getItems()) {
			buffer.append((item.getId() == null ? 0 : item.getId()) + "=" + item.getProductId() + "=" + item.getCount() + "=" + (item.getCartId() == null ? 0 : item.getCartId()) + "==");
		}
		return buffer.toString();
	}

	@Override
	public Cart translat(String cartStr) {
		Cart cart = new Cart();
		List<CartItem> items = cart.getItems();
		if (cartStr != null && !cartStr.equals("")) {
			String[] vals = cartStr.split("===");
			String[] cartVals = vals[0].split("=");
			cart.setId(Integer.parseInt(cartVals[0]));
			cart.setProvinceId(Integer.parseInt(cartVals[1]));
			cart.setCityId(Integer.parseInt(cartVals[2]));
			cart.setDistrictId(Integer.parseInt(cartVals[3]));
			
			String[] itemListVals = vals[1].split("==");
			for (String itemListVal : itemListVals) {
				String[] itemVals = itemListVal.split("=");
				CartItem item = new CartItem();
//				item.setId(Integer.parseInt(itemVals[0]));
				item.setProductId(Integer.parseInt(itemVals[1])); 
				item.setCount(Integer.parseInt(itemVals[2]));
//				item.setCartId(Integer.parseInt(itemVals[3]));
				items.add(item);
			}
		}
		return cart;
	}


	@Override
	public void saveWithMember(int userId, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Cart memberCart = cartMapper.selectByUserId(userId);
		Cart cart = this.getCartByCookie(request);
		if(cart.getItems().size() == 0 ){
			return;
		}
		if(memberCart != null){
//			memberCart.setProvince(cart.getProvince());
//			memberCart.setCity(cart.getCity());
//			memberCart.setDistrict(cart.getDistrict());
			memberCart.setUpdateTime(new Date());
			cartMapper.update(memberCart);
			for(CartItem item : cart.getItems()){
				CartItem temp = cartItemService.findByProductIdAndCartId(item.getProductId(),memberCart.getId());
				if(temp == null){
					item.setCartId(memberCart.getId());
					item.setCreateTime(new Date());
					cartItemService.save(item);
				}else{
					temp.setCount(temp.getCount() + item.getCount());
					temp.setUpdateTime(new Date());
					cartItemService.update(temp);
				}
			}
		}else{
			cart.setUserId(userId);
			cart.setCreateTime(new Date());
			cartMapper.insert(cart);
			for(CartItem item : cart.getItems()){
				item.setCartId(cart.getId());
				item.setCreateTime(new Date());
				cartItemService.save(item);
			}
		}
		
		this.deleteByCookie(response);
	}

	@Override
	public Cart findByUserId(int userId) {
		return cartMapper.selectByUserId(userId);
	}

	@Override
	public void addWithMember(Cart currentCart, CartItem cartItem,int userId) {
		Cart memberCart = cartMapper.selectByUserId(userId);
		if(memberCart == null){
			memberCart = currentCart;
			memberCart.setUserId(userId);
			memberCart.setCreateTime(new Date());
			cartMapper.insert(memberCart);
		}else{
//			memberCart.setProvince(currentCart.getProvince());
//			memberCart.setCity(currentCart.getCity());
//			memberCart.setDistrict(currentCart.getDistrict());
			cartMapper.update(memberCart);
		}
		CartItem item = cartItemService.findByProductIdAndCartId(cartItem.getProductId(),memberCart.getId());
		if(item == null){
			cartItem.setCartId(memberCart.getId());
			cartItem.setCreateTime(new Date());
			cartItemService.save(cartItem);
		}else{
			item.setCount(cartItem.getCount() + item.getCount());
			item.setUpdateTime(new Date());
			cartItemService.update(item);
		}
	}
	
	/**
	 * 从cookie中清空购物车
	 * 
	 * @author Karlzhou
	 * @return
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	@Override
	public void clearByCookie(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 获取当前用户购物车cookie
		Cookie cartCookie = CookieUtil.getCookieByName(request, "shopcart");
		String cartStr = URLDecoder.decode(cartCookie.getValue(), "utf-8");
		if (cartStr != null && !cartStr.equals("")) {
			String[] vals = cartStr.split("===");
			CookieUtil.addCookie(response, "shopcart", URLEncoder.encode(vals[0], "utf-8"), 3600 * 24 * 7);
		}
	}

	/**
	 * 清空当前会员的购物车
	 * 
	 */
	@Override
	public void clearByUserId(int userId) {
		Cart cart = cartMapper.selectByUserId(userId);
		if(cart != null){
			cartItemService.delete(cart.getId());
			cartMapper.delete(cart.getId());
		}
	}

	/**
	 * 删除购物车中某个商品项
	 */
	@Override
	public void deleteItemByProductId(int productId, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Cart cart = this.getCartByCookie(request);
		Iterator<CartItem> itr = cart.getItems().iterator();
		while(itr.hasNext()){
			if(itr.next().getProductId() == productId){
				itr.remove();
			}
		}
		
		String cartStr = this.parse(cart);
		//System.out.println("cart str : " + cartStr);
		if (cartStr != null && !"".equals(cartStr)) {
			cartStr = cartStr.substring(0, cartStr.length() - 2);
			CookieUtil.addCookie(response, "shopcart", 
						URLEncoder.encode(cartStr, "utf-8"), 3600 * 24 * 7);
			
		}
		
	}

	@Override
	public void deleteWithMember(int userId, int productId) {
		Cart memberCart = cartMapper.selectByUserId(userId);
		
		Iterator<CartItem> itr = memberCart.getItems().iterator();
		while(itr.hasNext()){
			CartItem item = itr.next();
			if(item.getProductId() == productId){
				cartItemService.deleteById(item.getId());
			}
		}
		
	}

	@Override
	public void deleteByCookie(HttpServletResponse response) throws Exception {
		CookieUtil.addCookie(response, "shopcart", null, 0);
	}

//	@Override
//	public Cart getCart(HttpServletRequest request) throws Exception {
//		Member member = (Member) request.getSession().getAttribute("member");
//		System.out.println("getCart member : " + member);
//		Cart cart = null;
//		if(member == null){
//			cart = this.getCartByCookie(request);
//		}else{
//			cart = cartMapper.selectByUserId(member.getUserId());
//		}
//		if(cart == null){
//			return new Cart();
//		}
//		if(cart.getItems().size() == 0){
//			return cart;
//		}
//		double totalAccount = 0.0;
//		int totalNum = 0;
//		for(CartItem item : cart.getItems()){
//			Product product = productService.findById(item.getProductId());
//			item.setProduct(product);
//			totalAccount += product.getShopPrice() * item.getCount();
//			totalNum += item.getCount();
//		}
//		cart.setTotalAccount(totalAccount);
//		cart.setTotalNum(totalNum);
//		return cart;
//	}

	@Override
	public Cart findForConfirmByUserId(int userId) {
		return cartMapper.selectForConfirmByUserId(userId);
	}

}
